package com.empl.mgr.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.empl.mgr.constant.PageConstant;
import com.empl.mgr.dao.EmployeesBasicDao;
import com.empl.mgr.dao.LeaveDao;
import com.empl.mgr.dto.LeaveInfoDto;
import com.empl.mgr.field.TeLeaveField;
import com.empl.mgr.model.TeLeave;
import com.empl.mgr.service.LeaveService;
import com.empl.mgr.support.JSONReturn;
import com.empl.mgr.utils.CompareUtil;
import com.empl.mgr.utils.DateTimeUtil;
import com.empl.mgr.utils.PageUtils;

@Scope
@Service
@Transactional(readOnly = true)
public class LeaveServiceImpl implements LeaveService {

	
	
	
	
	
	
	
	@Autowired
	private EmployeesBasicDao employeesBasicDao;
	
	
	@Autowired
	private LeaveDao leaveDao;
	
	
	@Autowired
	ProcessEngine processEngine;
	
	
	public JSONReturn findAllLeaveList(int page) {
		
		
		List<Task> allTaskList = processEngine.getTaskService()
				 .createTaskQuery()
				 .list();
		
		
		List <TeLeave> leaveList = null;
		List <LeaveInfoDto> dtoList = new ArrayList<LeaveInfoDto>();
		leaveList = leaveDao.findLeaveList(page);
		if (CollectionUtils.isEmpty(leaveList))
			return JSONReturn.buildFailure("未获取到相关数据!");
		for(TeLeave te : leaveList){
			LeaveInfoDto leaveDto = new LeaveInfoDto();
			leaveDto.setId(te.getLeaveId());
			leaveDto.setEmId(te.getEmployeesId());
			leaveDto.setEmployeesName(employeesBasicDao.findById(te.getEmployeesId()).getEmFullName());
			leaveDto.setStartTime(te.getStartTime());
			leaveDto.setEndTime(te.getEndTime());
			leaveDto.setLeaveReason(te.getLeaveReason());
			if(allTaskList == null){
				continue;
			}
			for(Task task : allTaskList){
				if(task.getProcessInstanceId().equals(String.valueOf(te.getLeaveId()))){
					leaveDto.setLeaveCurrentNode(task.getName());
					leaveDto.setFlowState(true);
					break;
				}
			}
			
			
			leaveDto.setLeaveCreateTime(te.getCreateTime().toString());
			dtoList.add(leaveDto);
			
		}
		
		return JSONReturn.buildSuccess(dtoList);
	}
	
	public JSONReturn findAllMyLeaveList(int page, String acctName) {

		if (acctName.equals("kaoqinguanli") || acctName.equals("admin")) {
			return findAllLeaveList(page);
		}

		List<Task> allTaskList = processEngine.getTaskService().createTaskQuery().taskAssignee(acctName).listPage(page-1, PageConstant.PAGE_LIST);
		
		List<TeLeave> leaveList = null;
		List<LeaveInfoDto> dtoList = new ArrayList<LeaveInfoDto>();
		leaveList = leaveDao.findAll();
		if (CollectionUtils.isEmpty(leaveList) || CollectionUtils.isEmpty(allTaskList))
			return JSONReturn.buildFailure("未获取到相关数据!");

		for (Task task : allTaskList) {
			for (TeLeave te : leaveList) {
				if (task.getProcessInstanceId().equals(String.valueOf(te.getLeaveId()))) {
					LeaveInfoDto leaveDto = new LeaveInfoDto();
					leaveDto.setId(te.getLeaveId());
					leaveDto.setEmId(te.getEmployeesId());
					leaveDto.setEmployeesName(employeesBasicDao.findById(te.getEmployeesId()).getEmFullName());
					leaveDto.setStartTime(te.getStartTime());
					leaveDto.setEndTime(te.getEndTime());
					leaveDto.setLeaveReason(te.getLeaveReason());
					leaveDto.setLeaveCurrentNode(task.getName());
					leaveDto.setFlowState(true);
					leaveDto.setLeaveCreateTime(te.getCreateTime().toString());
					dtoList.add(leaveDto);
				}
			}
		}

		return JSONReturn.buildSuccess(dtoList);
	}
	
	
	
	
	public JSONReturn findLeavePage(int page) {
		int count = leaveDao.findLeavePage();
		return JSONReturn.buildSuccess(PageUtils.calculatePage(page, count, PageConstant.PAGE_LIST));
	}
	
	public JSONReturn findMyLeavePage(int page, String acctName) {
		int count;
		if (acctName.equals("kaoqinguanli") || acctName.equals("admin")) {
			count = leaveDao.findLeavePage();
		}else{
			count = processEngine.getTaskService().createTaskQuery().taskAssignee(acctName).list().size();
			
		}
		return JSONReturn.buildSuccess(PageUtils.calculatePage(page, count, PageConstant.PAGE_LIST));
	}



	@Transactional
	public JSONReturn addLeave(long emId, String startDate, String endDate, String leaveReason, String acctName) {
		if (emId <=0 || StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate) || StringUtils.isEmpty(leaveReason))
			return JSONReturn.buildFailure("添加失败,有数据项为空!");
		
		if(employeesBasicDao.findById(emId) == null ){
			return JSONReturn.buildFailure("添加失败,该员工不存在，请检查是否输入错误!");
		};
		
		
		TeLeave teLeave = new TeLeave();
		teLeave.setLeaveId(Long.parseLong(processEngine.getRuntimeService()
	             .startProcessInstanceByKey("DemoProcess").getId()));
		teLeave.setEmployeesId(emId);
		teLeave.setStartTime(startDate);
		teLeave.setEndTime(endDate);
		teLeave.setCreateTime(DateTimeUtil.getCurrentTime());
		teLeave.setLeaveReason(leaveReason);
		teLeave.setTimestamp(DateTimeUtil.getCurrentTime());

		leaveDao.save(teLeave);
		
		return JSONReturn.buildSuccess("添加成功!");
	}
	
	
	public JSONReturn findLeaveById(long id) {
		TeLeave teLeave = leaveDao.findById(id);
		
		
		if (CompareUtil.isEmpty(teLeave))
			return JSONReturn.buildFailure("操作失败, 源数据不存在");
		return JSONReturn.buildSuccess(teLeave);
		
	}



	@Transactional
	public JSONReturn verifyLeave(long id, boolean checkResult, String checkReason, String acctName) {
		
		List<Task> taskList = processEngine.getTaskService()
				 .createTaskQuery().processInstanceId(String.valueOf(id))
				 .list();
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put(acctName+"的审核意见:", checkReason);
		/*if(acctName.equals("renliguihua")){
			if(checkResult){
				variables.put("firstAudit", "1");
			}else{
				variables.put("firstAudit", "0");
			}
			
		}else if(acctName.equals("renlizhuren")){
			if(checkResult){
				variables.put("secondAudit", "1");
			}else{
				variables.put("secondAudit", "0");
			}
		}*/
		
		if(checkResult){
			variables.put("firstAudit", "1");
			variables.put("secondAudit", "1");
		}else{
			variables.put("firstAudit", "0");
			variables.put("secondAudit", "0");
		}
	
		
		
		processEngine.getTaskService().complete(taskList.get(0).getId(), variables);;
		
		
		return JSONReturn.buildSuccess("审批员工请假单成功!");
	}



	@Transactional
	public JSONReturn submitLeave(long id, String acctName) {
		List<Task> taskList = processEngine.getTaskService()
				 .createTaskQuery().processInstanceId(String.valueOf(id))
				 .list();
		processEngine.getTaskService().complete(taskList.get(0).getId());;
		
		
		return JSONReturn.buildSuccess("提交员工请假单成功!");
	}



	@Transactional
	public JSONReturn updateLeave(long updateLeaveId, String startDate, String endDate, String leaveReason,
			String acctName) {
		if (updateLeaveId <=0 || StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate) || StringUtils.isEmpty(leaveReason))
			return JSONReturn.buildFailure("添加失败,有数据项为空!");
		TeLeave teLeave = leaveDao.findUniqueByProperty(TeLeaveField.Leave_ID, updateLeaveId);
		
		
		teLeave.setStartTime(startDate);
		teLeave.setEndTime(endDate);
		teLeave.setLeaveReason(leaveReason);
		teLeave.setTimestamp(DateTimeUtil.getCurrentTime());

		
		return JSONReturn.buildSuccess("修改成功!");
		
	}
	@Transactional
	public JSONReturn deleteLeave(long id, String acctName) {
		processEngine.getRuntimeService().deleteProcessInstance(String.valueOf(id), acctName+DateTimeUtil.getCurrentTime()+"删除");
		leaveDao.delete(leaveDao.findById(id));
		return JSONReturn.buildSuccess("删除成功!");
	}
	

}
